package pl.nazaweb.samplesandtutorials.adapters;

import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

public class ImageAdapter extends BaseAdapter {

	private List<Integer> resourceImages;
	private Bitmap[] imageBitmaps;
	private Bitmap[] imageMiniatures;
	private Context context;
	private LayoutInflater layoutInflater;

	public ImageAdapter(Context context, List<Integer> resourceImages) {
		this.resourceImages = resourceImages;
		this.context = context;
		layoutInflater = LayoutInflater.from(context);
		initImages();
	}

	private void initImages() {
		imageBitmaps = new Bitmap[resourceImages.size()];
		imageMiniatures = new Bitmap[resourceImages.size()];
		for (int x = 0; x < resourceImages.size(); x++) {
			decodeImageBitmapAtIndex(x);
			createMiniatureToImageAtIndex(x);
		}
	}

	private void createMiniatureToImageAtIndex(int x) {
		imageMiniatures[x] = ThumbnailUtils.extractThumbnail(imageBitmaps[x],
				60, 60);
	}

	private void decodeImageBitmapAtIndex(int x) {
		imageBitmaps[x] = BitmapFactory.decodeResource(context.getResources(),
				resourceImages.get(x));
	}

	static class ViewHolder {
		ImageView image;
	};

	public int getCount() {
		return resourceImages.size();
	}

	public Object getItem(int position) {
		return imageBitmaps[position];
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder viewHolder;
		if (convertView == null) {
			convertView = layoutInflater.inflate(
					pl.nazaweb.samplesandtutorials.R.layout.gridimage, null);
			viewHolder = new ViewHolder();
			viewHolder.image = (ImageView) convertView
					.findViewById(pl.nazaweb.samplesandtutorials.R.id.gridimage);
			convertView.setTag(viewHolder);
		}else{
			viewHolder = (ViewHolder)convertView.getTag();
		}
		viewHolder.image.setImageBitmap(imageMiniatures[position]);
		return convertView;
	}

}
